package org.bookie.web.pages.admin;

import org.apache.tapestry.IPage;
import org.apache.tapestry.annotations.InjectComponent;
import org.apache.tapestry.annotations.InjectObject;
import org.apache.tapestry.annotations.Persist;
import org.apache.tapestry.dojo.html.Dialog;
import org.apache.tapestry.event.PageBeginRenderListener;
import org.apache.tapestry.event.PageEvent;
import org.bookie.framework.CommonBasePage;
import org.bookie.model.Event;
import org.bookie.model.Role;
import org.bookie.model.security.Access;
import org.bookie.model.services.EventDAO;

/**
 * This page is used by a bookmaker to crate a new {@link Event} to bet on. 
 * After filling out the form bookmaker have to confirm the event before it will be saved.
 * 
 * @author Igor Drobiazko
 *
 */
@Access(role = Role.ADMIN)
public abstract class AddEvent extends CommonBasePage implements
		PageBeginRenderListener {
	
	/**Client identifier of the content div*/
	public static final String CONTENT = "content";
	
	/**Client identifier of the confirmation dialog shown before an Event is saved*/
	public static final String CONFIRM_SAVE_DIALOG = "confirmSaveDialog";
	
	/**
	 * {@inheritDoc}
	 */
	public void pageBeginRender(PageEvent event) {
		if(getEvent()==null){
			setEvent(new Event(null, null, null));
		}
	}
	
	/**
	 * Listener method invoked to validate the input data and to show the confirmation dialog.
	 */
	public IPage confirmEvent() {
		getDialog().show();
		return this;
	}
	
	/**
	 * Listener method invoked by the confirmation dialog to store a new {@link Event}
	 */
	public IPage addEvent() {
		getEventDAO().makePersistent(getEvent());
		reset();
		setMessage(getMessages().getMessage("admin.addevent.success.message"));
		updateComponents(CONTENT);
		return this;
	}
	
	/**
	 * Resets the page
	 */
	private void reset() {
		setEvent(null);
	}
	
	/**
	 * Injected {@link EventDAO} service.
	 * @return instance of EventDAO
	 */
	@InjectObject("service:bookie.model.EventDAO")
	public abstract EventDAO getEventDAO();
	
	/**
	 * Injected {@link Dialog} component.
	 * The client identifier of this component is {@value #CONFIRM_SAVE_DIALOG}
	 */
	@InjectComponent(CONFIRM_SAVE_DIALOG)
	public abstract Dialog getDialog();
	
	/**
	 * Get the {@link Event} to be saved
	 */
	@Persist("session")
	public abstract Event getEvent();
	
	/**
	 * Set the {@link Event} to be saved
	 * @param event event to set
	 */
	public abstract void setEvent(Event event);
}
